package ServiceDataFresh

import (
	"bytes"
	"fmt"
	"net"
	"os"
	"strings"
	"ustcLab/server/dao/bean"
)

func NewHandlerRecv() {
	netListen, err := net.Listen("tcp", ":8102")
	if err != nil {
		fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
	}
	defer netListen.Close()
	fmt.Println("Waiting for clients ...")

	//等待客户端访问
	for {
		conn, err := netListen.Accept() //监听接收
		if err != nil {
			continue //如果发生错误，继续下一个循环。
		}
		fmt.Println(conn.RemoteAddr().String(), "tcp connect success") //tcp连接成功
		go handleConnection(conn)
	}
}

//处理连接
func handleConnection(conn net.Conn) {
	raw := make([]byte, 2048) //建立一个slice
	n, err := conn.Read(raw)
	if err != nil {
		fmt.Println(conn.RemoteAddr().String(), "connection error: ", err)
		return //当远程客户端连接发生错误（断开）后，终止此协程。
	}
	//根据字符匹配选择机器
	if strings.IndexAny(string(raw[:n]), "MINDRAY_N-SERIES") > -1 {
		handleMINDRAY(conn, raw, n)
	} else {
		return
	}

}

//MINDRAY型号仪器数据处理
func handleMINDRAY(conn net.Conn, raw []byte, n int) {
	var buf bytes.Buffer
	k := 0          //用来判断凑成3个包
	var mark string //用作标志判断MSH是否为同一秒的数据
	cacheMap := make(map[int]string)
	for {
		buf.Write(raw[:n])
		msg, buf1 := split(buf.String())
		//fmt.Println(buf1)
		//fmt.Println(len(msg))
		//这个msg字符数组存完整的MSH包，为0时表示收到的数据没有凑成一个完整的MSH包
		if len(msg) != 0 {
			buf.Reset()
			buf.WriteString(buf1)
			for _, bits := range msg {
				//一个包一个包的加入，每次加入缓冲区前获取时间，缓冲区为空时，用第一个时间为基准判断，连续3个相同时间则取出来一起解析，并把缓冲区清空，期间碰到不同时间的则清空缓冲区，用该时间为基准重新开始。
				//fmt.Printf(bits)
				index := strings.Index(bits, "||||")
				tag := bits[index+4 : index+21]
				fmt.Println(tag)
				if k == 0 {
					mark = tag
				}
				if mark == tag {
					k++
					cacheMap[k] = bits
					if k == 3 {
						//去解析
						analyse(cacheMap)
						cacheMap = make(map[int]string)
						k = 0
					}
				} else {
					mark, k = tag, 1
					cacheMap = make(map[int]string) //清空原来的cacheMap
					cacheMap[k] = bits
				}
			}
		}
		raw = make([]byte, 2048) //建立一个slice
		var err error
		n, err = conn.Read(raw) //读取客户端传来的内容
		if err != nil {
			fmt.Println(conn.RemoteAddr().String(), "connection error: ", err)
			return //当远程客户端连接发生错误（断开）后，终止此协程。
		}
	}
}

//开始提取接受到的1s的数据
func analyse(cacheMap map[int]string) {
	//fmt.Println(cacheMap)
	tPythonData := &bean.TPythonData{
		Date:                "",
		PULS_OXIM_SAT_O2:    "",
		PULS_OXIM_PULS_RATE: "",
		BLD_PERF_INDEX:      "",
		WaveData:            make([]map[string]string, 3),
	}
	for key, value := range cacheMap {
		if key == 1 {
			index := strings.Index(value, "||||")
			tPythonData.Date = value[index+4 : index+21] //时间
			tPythonData.PULS_OXIM_PULS_RATE = findPoint(value, "PULS_OXIM_PULS_RATE")
			tPythonData.BLD_PERF_INDEX = findPoint(value, "BLD_PERF_INDEX")
			tPythonData.PULS_OXIM_SAT_O2 = findPoint(value, "PULS_OXIM_SAT_O2")

		} else if key == 2 {
			tPythonData.WaveData[0] = findWavePoint(value, "ECG_ELEC_POTL_II")
		} else if key == 3 {
			tPythonData.WaveData[1] = findWavePoint(value, "PULS_OXIM_PLETH")
			tPythonData.WaveData[2] = findWavePoint(value, "IMPED_TTHOR")
		}
	}
	fmt.Println(tPythonData)
	//调用数据结构转换代码
	NewDataTransfer(tPythonData)
}

//提取波形数据
func findWavePoint(value, str string) map[string]string {
	hashMap := make(map[string]string)
	var newStr []string
	index := strings.Index(value, str)
	if index > -1 {
		value = value[index:]
		newStr = strings.Split(value, "|")
		hashMap[str] = newStr[2]
	} else {
		hashMap[str] = ""
	}

	index = strings.Index(value, "ATTR_SAMP_RATE")
	if index > -1 {
		value = value[index:]
		newStr = strings.Split(value, "|")
		hashMap["ATTR_SAMP_RATE"] = newStr[2]
	} else {
		hashMap["ATTR_SAMP_RATE"] = ""
	}

	index = strings.Index(value, "ATTR_NU_MSMT_RES")
	if index > -1 {
		value = value[index:]
		newStr = strings.Split(value, "|")
		hashMap["ATTR_NU_MSMT_RES"] = newStr[2]
	} else {
		hashMap["ATTR_NU_MSMT_RES"] = ""
	}

	index = strings.Index(value, "EVT_INOP")
	if index > -1 {
		value = value[index:]
		newStr = strings.Split(value, "|")
		x := strings.Index(newStr[2], "\r")
		hashMap["EVT_INOP"] = newStr[2][:x]
	} else {
		hashMap["EVT_INOP"] = ""
	}
	return hashMap
}

//提取单点数据
func findPoint(value, str string) string {
	index := strings.Index(value, str)
	if index > -1 {
		temp := value[index:]
		newStr := strings.Split(temp, "|")
		return newStr[2]
	} else {
		return ""
	}
}

func split(data string) ([]string, string) {
	message := strings.Split(data, "\x1c\r")
	n := len(message)
	data = message[n-1]
	return message[:n-1], data
}
